<style scoped>

</style>
<template>
    <div class="create-inquiry-sheet-page">
       <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline" style="margin-bottom:20px;border-bottom:0px solid #ccc;">
            <el-form-item label="备件编码" :label-width="labelWidth">
                <el-input size="mini"  v-model="formInline.spareCoding  " placeholder="请输入备件编码"></el-input>
            </el-form-item>
            <el-form-item label="供应商编码" :label-width="labelWidth">
                <el-input size="mini"  v-model="formInline.vendorCode" placeholder="请输入供应商编码"></el-input>
            </el-form-item>
            <el-form-item label="有效开始日期"  prop="startTime"  :rules="[{ required: true, message: '询价开始日期不能为空'}]" :label-width="labelWidth100">
                <el-date-picker type="date" size="mini" :editable="false" :clearable="false" v-model="formInline.startTime" placeholder="选择询价开始日期" :picker-options="pickerOptions" @change="selectedStartTime"></el-date-picker>
            </el-form-item>
            <el-form-item label="有效结束日期" prop="endTime"  :rules="[{ required: true, message: '询价结束日期不能为空'}]" :label-width="labelWidth100">
                <el-date-picker type="date" size="mini" :editable="false" :clearable="false" v-model="formInline.endTime"  placeholder="选择询价结束日期日期" :picker-options="pickerOptions" @change="selectedEndTime"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button class="bolder outsideBtnBS" size="mini" type="danger"  @click="onSubmit(20)">一键生成有效价格</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                pickerOptions: {     //询价开始日期/结束日期不得早于当天
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                nowLangue:{},
                labelWidth:"80px",
                labelWidth100:"100px",
                // 查询表单
                formInline:{
                    id:"",
                    requestForQuotationId:"",
                    quotationNumber:"",
                    biddingStatus:"",
                    createTime:"",
                    creatorName:"",
                    legalPersonId:"",
                    legalPersonName:"",
                    spareCoding:"",
                    vendorCoding:"",
                    type:"",
                    typeName:"",
                    currencyCode:"",
                    currencyCodeWord:"",
                    isTax:"",
                    isTaxName:"",
                    startTime:"",
                    endTime:"",
                    legalPersonNameList:[]
                },
                legalPersonDropDown:[],
                loading:false,
                inquiryDetailsData: [],// 待询价明细表格
                supplierDetailsData:[],// 待报价供应商明细
                biddingDetailsData:[],//报价明细
                selectDropdown:[],  // 下拉列表的值
                tableData:[],//报价列表数据
                spareData:[],    // 选择备件弹窗  
                formLabelWidth:"90",
                // 选择备件弹窗的 分页
                // isPaging:true,
                selectSparePartsVisible:false,   //选择备件弹窗
                selectSparePartsForm:{
                    spareCode:"",
                    spareName:""
                },
                //选择备件弹窗的 分页
                sparePageIndex:1,    //当前页（必传）
                sparePageSize :5,   //每页多少条
                spareTotalNumber: 20,     //总条数
                spareTotalPage:2,    //总页数

                // 选择供应商弹窗的  分页
                selectSuppliersVisible:false,
                selectSuppliersForm:{
                    supplierCode:"",
                    supplierName:""
                },
                supplierData:[], //新增供应商弹框中，供应商的信息
                providerList:[],//新增供应商弹框中，选中的供应商的信息
                supplierType:1,
                supplierPageIndex:1,    //当前页（必传）
                supplierPageSize :5,
                supplierTotalNumber: 20,     //总条数
                supplierTotalPage:2,

             
                leadIngInVisible:false,   //导入弹窗
                action:"",
                fileList:[],

                inquiryDetailsList:[],   //修改传的一个参数（表格）
                supplierDetailsList:[],
                //查询禁用
                selectDisabled:false
            };
        },
        created:function(){
            var _this=this;
            _this.languageType=="zh"?_this.nowLangue=_this.language.zh:_this.nowLangue=_this.language.en;
        },
        computed:{
            // powerData(){
            //     return this.$store.state.powerData;
            // },
            languageType(){
                return this.$store.state.languageType;
            }
        },
        watch:{
            languageType(){
                var _this=this;
                _this.languageType=="zh"?_this.nowLangue=_this.language.zh:_this.nowLangue=_this.language.en;
            }
        },
        //进入页面立即运行此方法
        mounted: function () {
            var _this = this;
            // //ajax前后查询按钮禁用
            // $(".selectAll").ajaxStart(function(){
            //     _this.selectDisabled=true;
            // });
            // $(".selectAll").ajaxStop(function(){
            //     _this.selectDisabled=false;
            // });
        },
        methods: {
            // 选择询价开始日期
            selectedStartTime(val){
                var _this=this;
                _this.formInline.startTime = val;
                if(_this.formInline.endTime && val >= _this.formInline.endTime){
                    _this.common.errorTip("询价开始日期不能大于等于询价结束日期");
                    _this.formInline.startTime = "";
                };
            },
            // 选择询价结束日期
            selectedEndTime(val){
                var _this=this;
                _this.formInline.endTime = val;
                if(_this.formInline.startTime && val <= _this.formInline.startTime){
                    _this.common.errorTip("询价结束日期不能小于等于询价开始日期");
                    _this.formInline.endTime = "";
                };
            },
            // 新增的接口  新增后保存/提交
            addData(inquiryStatus){
                var _this = this;
                var spareCode = _this.formInline.spareCoding;
                if(spareCode.indexOf(",")!=-1){
                     var arr=spareCode.split(",");
                     for(var i=0;i<arr.length;i++){
                        _this.inquiryDetailsData.push({
                            spareCoding:arr[i],
                            currencyCodeWord:'人民币',
                            currencyCode:'CNY',
                            spareName:'test',
                            inquiryQty:10,
                        });
                     }
                }else{
                     _this.inquiryDetailsData.push({
                        spareCoding:_this.formInline.spareCoding,
                        currencyCodeWord:'人民币',
                        currencyCode:'CNY',
                        spareName:'test',
                        inquiryQty:10,
                    });
                }

               var vendorCoding = _this.formInline.vendorCode;
                if(spareCode.indexOf(",")!=-1){
                     var arrV=vendorCoding.split(",");
                     for(var i in arrV){
                        _this.supplierDetailsData.push({
                            vendorCode:arrV[i],
                            vendor:'test'
                        });
                     }
                }else{
                    _this.supplierDetailsData.push({
                        vendorCode:_this.formInline.vendorCode,
                        vendor:'test'
                    });
                }
                var auditorTime=_this.getTime();
                var tmp = {currencyCode:'CNY',inquiryStatus:20,legalPersonId:47,type:1,isTax:1,startTime:auditorTime,
                endTime:auditorTime,inquiryDetailsList:_this.inquiryDetailsData,supplierDetailsList:_this.supplierDetailsData};
                console.log("新增后，保存提交");
                console.log(tmp);
                $.ajax({
                    url:_this.procurement_service+'inquiryList/add',
                    type:'POST',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            _this.common.successTip("询价单创建成功！");
                            _this.formInline.requestForQuotationId=data.data.requestForQuotationId;   //询价单号
                            _this.formInline.createTime=data.data.createTime;   //询价日期
                            if(inquiryStatus==20){
                                _this.toExamine(1);
                            }
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
             // 获取当前时间
            getTime(){
                var myDate=new Date();
                var year=myDate.getFullYear();
                var month=myDate.getMonth()+1;
                var day=myDate.getDate();
                var hours=myDate.getHours();
                var minutes=myDate.getMinutes();
                var seconds=myDate.getSeconds();
                var time = year +"-"+ month +"-"+ day +" "+ hours +":"+ minutes +":"+ seconds;
                return time;
            },
            //提交按钮
            onSubmit(inquiryStatus){
                var _this = this;
                _this.$refs["formInline"].validate((valid) => {
                    if (valid) {
                         _this.addData(20);
                    } else {
                        _this.common.errorTip("存在未填写的必填项！");
                        return false;
                    }
                });
            },
            toExamine(auditorStatus){   //1 审核通过  0审核不通过
                var _this = this;
                var auditorExplainArea = "";
                var tmp = {requestForQuotationId:_this.formInline.requestForQuotationId,auditorExplain:auditorExplainArea,auditorStatus:auditorStatus};
                $.ajax({
                    url:_this.procurement_service+'inquiryAuditor/update',
                    type:'POST',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            _this.common.successTip("询价单审核成功！");
                            _this.examinationAndApproval(1);
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            examinationAndApproval(approverStatus){ //1 审批通过  0审批不通过
                var _this = this;
                var approverExplainArea = "";
                var tmp = {requestForQuotationId:_this.formInline.requestForQuotationId,approverExplain:approverExplainArea,approverStatus:approverStatus};
                $.ajax({
                    url:_this.procurement_service+'inquiryApprover/update',
                    type:'POST',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            _this.common.successTip("询价单审批成功！");
                            //审批成功后，获取到报价列表的数据
                            _this.searchQuotationList();
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            // 查询报价列表
            searchQuotationList(){
                var _this=this;
                _this.loading=true;
                //待报价数据
                var tmp={
                    //legalPersonId: 47,
                    requestForQuotationId: _this.formInline.requestForQuotationId,
                    pageIndex: 1,
                    pageSize: 10
                };
                $.ajax({
                    type: 'POST',
                    url: _this.procurement_service+"quotationList/searchPre",
                    cache: false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            _this.loading=false;
                            var arr=data.data.dataList;
                            //单价保留八位
                            for(var i=0;i<arr.length;i++){
                                if(arr[i].quotationAmount){
                                    arr[i].quotationAmount=arr[i].quotationAmount.toFixed(8);
                                }
                            }
                            _this.tableData=arr;
                            _this.isPaging=true;
                            _this.totalPage=data.data.totalPage;
                            _this.totalNumber=data.data.totalNumber;
                            var newData=[];
                            var newDataCode=[];
                            //获取到报价列表数据后，拿数据创建报价单。
                            //把供应商的id获取到
                            for(var i=0;i<_this.tableData.length;i++){
                                if(newData.indexOf(_this.tableData[i].vendorCode)==-1)newData.push(_this.tableData[i].vendorCode)
                            }
                            var newDataList = newData;
                            for(var i=0;i<newDataList.length;i++){
                                var  vendorCode = newDataList[i];
                                for(var i1=0;i1<_this.tableData.length;i1++){
                                    if(_this.tableData[i1].vendorCode==vendorCode)newDataCode.push(_this.tableData[i1].spareCoding)
                                }
                                (function(i){
                                    _this.addQuotaitonData(vendorCode,newDataCode);
                                    console.log("查询报价列表");
                                    console.log(vendorCode);
                                    console.log(newDataCode);
                                    newDataCode.splice(0,newDataCode.length);//清空数组
                                })(i)
                            }
                        }else
                            _this.common.errorTip(data.errorMessage);
                    }
                });
            },
            // 新增的接口  新增后保存/提交
            addQuotaitonData(vendorCode,newDataCode){
                var _this = this;
                    for(var i in newDataCode){
                    _this.biddingDetailsData.push({
                        spareCoding:newDataCode[i],
                        currencyCodeWord:'人民币',
                        currencyCode:'CNY',
                        spareName:'test',
                        quotedQuantity:10,
                        quantityAvailable:10,
                        includingTaxPrice:10,
                        quotationAmount:10,
                        taxRate:0,
                        moq:10,
                        deliveryCycle:10,
                    });
                    }
                var tmp = {legalPersonName:'test',vendorCode:vendorCode,vendor:'testVendor',
                totalQuantityQuoted:20,totalQuotedPrice:'200',totalQuotedTaxPrice:200,exchangeRate:1,vendorId:2,
                quantityAvailable:20,currencyCode:'CNY',biddingStatus:20,bidder:111,legalPersonId:47,biddingType:1,
                isTax:1,startTime:_this.formInline.startTime,endTime:_this.formInline.endTime,quotationItem:_this.biddingDetailsData};
                $.ajax({
                    url:_this.procurement_service+'quotation/add',
                    type:'POST',
                    async: false,//同步请求数据
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            // _this.common.successTip("新增报价单成功！");
                            _this.formInline.biddingStatus=data.data.biddingStatus;
                            _this.formInline.quotationNumber=data.data.quotationNumber;   //报价单号
                            _this.formInline.createTime=data.data.createTime;   //报价日期
                            //_this.biddingDetailsData=data.data.quotationItem;
                            if(_this.formInline.biddingStatus==20){
                                console.log("新增报价单成功================");
                                console.log(data.data);
                                _this.toQuotationExamine(1);
                            }
                            _this.biddingDetailsData.splice(0,_this.biddingDetailsData.length);//清空数组
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            toQuotationExamine(auditorStatus){   //1 审核通过  0审核不通过
                var _this = this;
                var approverExplainArea = "";
                var tmp = {quotationNumber:_this.formInline.quotationNumber,auditorExplain:"",auditorStatus:auditorStatus};
                $.ajax({
                    url:_this.procurement_service+'quotationAuditor/update',
                    type:'POST',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            // _this.common.successTip("报价单审核成功！");
                            _this.formInline.biddingStatus = 30;
                            console.log("报价单审核成功！=======================");
                            console.log(_this.formInline.biddingStatus);
                            _this.QuotationExaminationAndApproval(1);
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            QuotationExaminationAndApproval(approverStatus){ //1 审批通过  0审批不通过
                var _this = this;
                var tmp = {quotationNumber:_this.formInline.quotationNumber,approverExplain:"",approverStatus:approverStatus};
                $.ajax({
                    url:_this.procurement_service+'quotationApprover/update',
                    type:'POST',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        if(data.success){
                            _this.common.successTip("报价单审批成功！");
                            _this.formInline.biddingStatus = 40;
                            console.log("报价单审批成功！=======================");
                            console.log(_this.formInline.biddingStatus);
                            //报价单审批过后，确认报价单，生成有效价格。
                            _this.confirmForSingle();
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            //按报价单确认
            //审核通过不通过
            confirmForSingle(){
                var _this = this;
                var tmp = {quotationNumber:_this.formInline.quotationNumber};
                $.ajax({
                    type: 'POST',
                    url: _this.procurement_service + "/quotationForSingleConfirm/update",
                    cache: false,
                    data: JSON.stringify(tmp),
                    dataType: 'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            // _this.common.successTip("已生成有效价格！");
                            console.log("已生成有效价格！=======================");
                        } else {
                            _this.common.errorTip(data.errorMessage);
                            _this.handleApprovalVisible = false;
                        }
                    }
                });
            },
            // successTip(p) {     //成功时的提示信息
            //     this.$notify({
            //         title: '成功',
            //         message: p,
            //         type: 'success'
            //     });
            // },
            // errorTip(p) {     //错误提示
            //     this.$notify.error({
            //         title: '错误',
            //         message: p
            //     });
            // }

        }
    }
</script>
<style scoped>
    .el-select .el-tag{
        margin: 0;
    }
    .el-select__tags .el-select__input {
        display: none;
    }
    .main-right .el-pagination{
        margin-top: 0;
    }
</style>